package com.lagou.rpc;

import com.lagou.configBean.ZkClient;
import com.lagou.handler.UserClientHandler;
import com.lagou.protocol.JSONSerializer;
import com.lagou.protocol.RpcEncoder;
import com.lagou.protocol.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ascetic
 * @version 1.0
 * @ClassName DiscoverService
 * @Description TODO
 * @date 2020-07-03 20:07
 */
public class DiscoverService {

    private static FindLinkHandler findLinkHandler;

    private static Map<String, UserClientHandler> tcpLink = new HashMap<>();


    public static void discover(String serviceName) throws Exception {

        CuratorFramework client = ZkClient.getZKClient();
        Stat stat = client.checkExists().forPath(serviceName);
        if(null == stat)
            client.create().withMode(CreateMode.PERSISTENT).forPath(serviceName);


        PathChildrenCache pathChildrenCache = new PathChildrenCache(client,serviceName,true);
        pathChildrenCache.start(PathChildrenCache.StartMode.POST_INITIALIZED_EVENT);
        pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {

                if( event.getType() == PathChildrenCacheEvent.Type.CHILD_ADDED){
                    System.out.println("事件类型："  + event.getType() + "；操作节点：" + event.getData().getPath());
                    String node = event.getData().getPath();
                    String [] linkInfo = node.substring(node.lastIndexOf("/")).split(":");
                    initClient(linkInfo[0],Integer.valueOf(linkInfo[1]));

                }
                if(event.getType() == PathChildrenCacheEvent.Type.CHILD_REMOVED){
                    System.out.println("事件类型："  + event.getType() + "；操作节点：" + event.getData().getPath());

                    String node = event.getData().getPath();
                    String [] linkInfo = node.substring(node.lastIndexOf("/")).split(":");
                    closeClient(linkInfo[0],Integer.valueOf(linkInfo[1]));


                }
            }
        });
    }


    //3.编写方法,初始化客户端  ( 创建连接池  bootStrap  设置bootstrap  连接服务器)
    public static void initClient(String ip,int port) throws InterruptedException {

        //1) 初始化UserClientHandler
        UserClientHandler userClientHandler  = new UserClientHandler();
        //2)创建连接池对象
        EventLoopGroup group = new NioEventLoopGroup();
        //3)创建客户端的引导对象
        Bootstrap bootstrap =  new Bootstrap();
        //4)配置启动引导对象
        bootstrap.group(group)
                //设置通道为NIO
                .channel(NioSocketChannel.class)
                //设置请求协议为TCP
                .option(ChannelOption.TCP_NODELAY,true)
                //监听channel 并初始化
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        //获取ChannelPipeline
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        //设置编码
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast( new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        //添加自定义事件处理器
                        pipeline.addLast(userClientHandler);
                    }
                });

        //5)连接服务端
        bootstrap.connect(ip,port).sync();
        tcpLink.put(ip+":"+port,userClientHandler);

    }

    // 通过userClientHandler 封装的 ChannelHandlerContext 关闭连接
    public static void closeClient(String ip,int port) throws InterruptedException {

        tcpLink.remove(ip+":"+port);
        tcpLink.get(ip+":"+port).getContext().close();

    }

    public static Map<String, UserClientHandler> getTcpLink() {
        return tcpLink;
    }

    public static UserClientHandler userClientHandlerFromMap() {
        return findLinkHandler.findLink(tcpLink);
    }

    public static void setFindLinkHandler(FindLinkHandler findLinkHandler) {
        DiscoverService.findLinkHandler = findLinkHandler;
    }
}